import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
export type StateStore = {
	/**请求安全锁时间 */
	_throttle_time: number
	/**储存请求安全锁key, */
	_throttle_data: { [key: string]: { lock: boolean; time: number; thread: null } }
}
type IStore = StateStore & {
	reg: (key: string, time?: number) => { lock: boolean; time: number; thread: null | NodeJS.Timer }
	lock: (key: string, time?: number) => void
	unLock: (key: string) => void
	isLock: (key: string) => boolean
	getData: (key: string) => { lock: boolean; time: number; thread: null | NodeJS.Timer } | undefined
}
const initialState: StateStore = {
	_throttle_time: 3 * 1000,
	_throttle_data: {},
}
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		reg: (key, time) => {
			const { _throttle_time, _throttle_data } = get()
			let _time = time || _throttle_time
			let result = Object.assign({}, _throttle_data, { [key]: { lock: false, time: _time, thread: null } })
			set({ _throttle_data: result })
			return result[key]
		},
		lock: (key, time) => {
			const { getData, reg, _throttle_data } = get()
			let data = getData(key) || reg(key, time)
			data.thread && clearTimeout(data.thread)
			data.lock = true
			let result = Object.assign({}, _throttle_data, { [key]: data })
			set({ _throttle_data: result })
			if (time === -1) {
				return
			}
			data.thread = setTimeout(function () {
				data.lock = false
				let result = Object.assign({}, _throttle_data, { [key]: data })
				set({ _throttle_data: result })
			}, data.time)
		},

		unLock: (key) => {
			const { getData, reg, _throttle_data } = get()
			let data = getData(key)
			if (!data) {
				return
			}
			data.thread && clearTimeout(data.thread)
			setTimeout(() => {
				if (data) {
					data.lock = false
					let result = Object.assign({}, _throttle_data, { [key]: data })
					set({ _throttle_data: result })
				}
			}, 300)
		},

		isLock: (key) => {
			const { getData } = get()
			let data = getData(key)
			if (!data) {
				return false
			}
			return data.lock
		},

		getData: (key) => {
			const { _throttle_data } = get()
			return _throttle_data[key]
		},
	}))
)
export const useLockStore = create(store)
